#include "main.h"

void get_ReallyPos(int x1, int y1, int x2, int y2)
{
    reallyX = (x1 + x2) / 2;
    reallyY = (y1 + y2) / 2;
}

void split_and_store(const char *str)
{
    char temp[100];
    strcpy(temp, str);
    char *token = strtok(temp, ",");
    int values[4];
    int count = 0;

    while (token != NULL && count < 4)
    {
        values[count++] = atoi(token);
        token = strtok(NULL, ",");
    }

    if (count == 4)
    {
			if(values[0]==-1&&values[1]==-1)
			{
				frame_width = values[2];
				frame_height = values[3];
				//显示视频分辨率
				OLED_ShowString(3,1,"X:");
				OLED_ShowNum(3,3,values[2],4);
				OLED_ShowString(3,9,"Y:");
				OLED_ShowNum(3,11,values[3],4);
			}
			else
			{
				x1 = values[0];
        y1 = values[1];
        x2 = values[2];
        y2 = values[3];
        get_ReallyPos(x1, y1, x2, y2);
			}
        
    }
}

int main(void)
{
    Usart_Init();
    OLED_Init();
    Servo_Init();

    // 设置舵机标准
    Servo_SetLevelAngle(standradLevelAngle);
    Servo_SetVerticalAngle(standradVerticalAngle);

    Delay_ms(2000);

    middleX = frame_width / 2;
    middleY = frame_height / 2;

    while (1)
    {
        if (data_received == 1) // 如果接收到数据包
        {
            split_and_store(rx_buffer);
					//显示接受的坐标
            OLED_ShowNum(1, 1, x1, 3);
            OLED_ShowNum(1, 5, y1, 3);
            OLED_ShowNum(1, 9, x2, 3);
            OLED_ShowNum(1, 13, y2, 3);

            int levelDifference = middleX - reallyX;
            int verticalDifference = middleY -reallyY;

            int8_t rateLevelAngle = abs(levelDifference)/middleX*90;
            int8_t rateVerticalAngle = abs(verticalDifference)/middleY*90;

            if(levelDifference<=0)
            {
                LevelAngle = standradLevelAngle - rateLevelAngle;
            }
            else
            {
                LevelAngle = standradLevelAngle + rateLevelAngle;
            }
            
            if(verticalDifference>=0)
            {
                VerticalAngle = standradVerticalAngle - rateVerticalAngle;
            }
            else
            {
                VerticalAngle = standradVerticalAngle + rateVerticalAngle;
            }

            Servo_SetLevelAngle(LevelAngle);
            Servo_SetVerticalAngle(VerticalAngle);

						//显示旋转角度
            OLED_ShowSignedNum(2, 3, LevelAngle, 3);
            OLED_ShowSignedNum(2, 8, VerticalAngle, 3);
            data_received = 0;
        }
    }
}

void USART1_IRQHandler(void)
{
    if (USART_GetITStatus(USART1, USART_IT_RXNE) == SET)
    {
        // 读取接收到的数据
        char rx_data = USART_ReceiveData(USART1);

        // 存储到缓冲区直到遇到换行符
        if (rx_data != '\n' && rx_index < sizeof(rx_buffer))
        {
            rx_buffer[rx_index++] = rx_data;
        }
        else
        {
            rx_buffer[rx_index] = '\0'; // 结束字符串
            rx_index = 0;
            data_received = 1;
        }

        // 清除中断标志
        USART_ClearITPendingBit(USART1, USART_IT_RXNE);
    }
}
